package com.itheima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.mapper.StudentMapper;
import com.itheima.pojo.Emp;
import com.itheima.pojo.PageResult;
import com.itheima.pojo.Student;
import com.itheima.pojo.StudentQueryParam;
import com.itheima.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class StudentServiceImpl implements StudentService {

    @Autowired
    private StudentMapper studentMapper;

    //学员列表查询
    @Override
    public PageResult<Student> page(StudentQueryParam studentQueryParam) {
        //1.设置分页参数(PageHelper)
        PageHelper.startPage(studentQueryParam.getPage(),studentQueryParam.getPageSize());
        //2.执行查询
        List<Student> stuList = studentMapper.list(studentQueryParam.getName(),studentQueryParam.getDegree(),studentQueryParam.getClazzId());
        //3.解析查询结果并封装
        Page<Student> p = (Page<Student>) stuList;
        return new PageResult<>(p.getTotal(),p.getResult());
    }

    //删除学员
    @Override
    public void delete(Integer[] ids) {
        studentMapper.delete(ids);
    }

    //添加学员
    @Override
    public void addStu(Student student) {
        student.setCreateTime(LocalDateTime.now());
        student.setUpdateTime(LocalDateTime.now());
        studentMapper.insertStu(student);
    }

    //根据ID查询学员
    @Override
    public Student findById(Integer id) {
        return studentMapper.findById(id);
    }

    //修改学员
    @Override
    public void update(Student student) {
        studentMapper.update(student);
    }

    //违纪处理
    @Transactional(rollbackFor = {Exception.class})
    @Override
    public void updateViolation(Integer id, Integer score) {
        //1.查询学员是否存在
        Student student = studentMapper.findById(id);
        if (student == null){
            throw new RuntimeException("学员不存在");
        }
        //2.检验扣分是否合法
        if (score <= 0){
            throw new RuntimeException("扣分必须大于0");
        }
        //3.更新违纪分数
        short newScore = (short) ( student.getViolationScore() + score);
        student.setViolationScore(newScore);
        //4.增加违纪次数
        Short violationCount = student.getViolationCount();
        student.setViolationCount((short)(violationCount + 1));
        //5.调用studentMapper更新数据库
        studentMapper.update(student);
    }
}
